package io.dirac.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket userDocket(Environment env) {
        Profiles devProf = Profiles.of("dev");
        boolean onDev = env.acceptsProfiles(devProf);

        ParameterBuilder tokenParam = new ParameterBuilder();
        List<Parameter> params = new ArrayList<Parameter>();
        tokenParam.name("authorization").description("JWT Token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        params.add(tokenParam.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("User")
                .apiInfo(apiInfo())
                .enable(onDev)
                .select()
                .apis(RequestHandlerSelectors.basePackage("io.dirac.controller"))
                .paths(PathSelectors.ant("/**"))
                .build()
                .globalOperationParameters(params);
    }

    private ApiInfo apiInfo() {
        // 作者信息
        Contact contact = new Contact("Dirac", "http://diraclee.gitee.io/", "dirac@gmail.com");

        return new ApiInfo(
                "Dirac 的 Api 文档",
                "使用 Swagger 构建的文档",
                "1.0",
                "http://diraclee.gitee.io/",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>()
        );
    }
}